package leoner.javascript;

import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map.Entry;

import javax.script.Bindings;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.SimpleBindings;

public class ScriptDemo {
	public static void main(String[] args) throws Exception {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("JavaScript");
		for (ScriptEngineFactory e : manager.getEngineFactories()) {
			System.out.println(e.getEngineName());
			System.out.println(e.getEngineVersion());
		}
		Bindings vars = new SimpleBindings();
		vars.put("demoVar", "value set in scriptDemo.java");
		vars.put("strBuf", new StringBuffer("string buffer"));

		Reader scriptReader = new InputStreamReader(ScriptDemo.class
				.getResourceAsStream("DemoScript.js"));
		try {
			engine.eval(scriptReader, vars);
		} finally {
			scriptReader.close();
		}
		System.out.println("-----------------------------------");
		Object demoVar = vars.get("demoVar");
		System.out.println("[java] demoVar:" + demoVar);
		System.out.println(" java object:" + demoVar.getClass().getName());
		System.out.println();
		Object strBuf = vars.get("strBuf");
		System.out.println("[java] strBuf:" + strBuf);
		System.out.println("    Java object: " + strBuf.getClass().getName());
		System.out.println();
		Object newVar = vars.get("newVar");
		System.out.println("[Java] newVar: " + newVar);
		System.out.println("    Java object: " + newVar.getClass().getName());
		System.out.println();
		System.out.println("-----------------------------------");
		for(Entry e : vars.entrySet()){
			System.out.println("name:"+e.getKey()+"--value:"+e.getValue());
		}
	}
}
